﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using TileMapEditor.TileEngine;

namespace TileMapEditor
{
    public class Tile
    {
        public delegate void OnClick(object sender, EventArgs e);
       
        //Attributes
        private int tileID;
        private float opacity;
        private Rectangle bounds;
        private Texture2D tileImage;
        private Vector2 tilePosition;
        

        public event OnClick Clicked;

        public Texture2D Texture
        {
            get { return tileImage; }
            set
            {
                tileImage = value;
            }
        }

        public float Opacity 
        {
            set { opacity = value; }
        }

        //Constructor
        public Tile(int id, Texture2D tex, Vector2 pos)
        {
            tileID = id;
            tileImage = tex;
            tilePosition = pos;
            bounds = new Rectangle((int)pos.X, (int)pos.Y, 32, 32);
            opacity = 1; //default

        }

        public void Update(Camera camera, MouseState curState, MouseState prevState)
        {

            #region Click Checking
            //bounds = new Rectangle((int)(tilePosition.X - (camera.Position.X)), (int)(tilePosition.Y - (camera.Position.Y)), 32, 32);
            //Check if mouse is hovering over tile
            if (bounds.Contains(new Point(Mouse.GetState().X, Mouse.GetState().Y)))
            {
                //Check if left mouse button is clicked
                if (curState.LeftButton == ButtonState.Pressed
                    && prevState.LeftButton == ButtonState.Released)
                {
                    Clicked(this, new EventArgs());
                }
            }
            #endregion

        }

        public void Draw(SpriteBatch spriteBatch)
        {
            if (tileImage != null)
            {
                spriteBatch.Draw(tileImage, bounds, Color.White * opacity);
            }
        }

        public void ChangeTile(Texture2D texture, int idNum) 
        {
            this.Texture = texture;
            this.tileID = idNum;
        }

    }
}
